#pragma once 

#include<iostream>
#include<string>
 #include<string.h>
#include <cerrno>
#include<sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include"Log.hpp"
#include"comm.hpp"
#include "nocopy.hpp"

using namespace std;

const uint16_t defalutport = 888;
const int defalutsockfd = -1;
const int defaultsize = 1024;

class Udp_server : public oncopy
{
public:
    Udp_server(const string& ip, uint16_t port = defalutport)
        :_ip(ip)
        ,_port(port)
        ,_sockfd(defalutsockfd)
    {}

    void init()
    {
        /* 1.创建socket */
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        /* socket失败 */
        if(_sockfd < 0)
        {
            /* 日志打印 */
            lg.LogMessages(Fatal, "socket err, %d: %s\n", errno, strerror(errno));
            exit(Socket_Err);
        }

        lg.LogMessages(Info, "socket success, sockfd: %d\n", _sockfd);

        /* 2.绑定网络信息 */
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());//将ip4字节变网络序列.

        /* 将结构体的内容设置到内核里面 */
        int n = ::bind(_sockfd, (struct sockaddr* )&local, sizeof(local));
        if(n != 0)
        {
            lg.LogMessages(Fatal, "bind error, %d : %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
    }

    void start()
    {
        char buffer[defaultsize];
        for(;;)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) -1, 0, (struct sockaddr* )&peer, &len);

            if(n > 0)
            {
                buffer[n] = 0;
                cout << "client say# " << buffer << endl;
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr* )&peer, len);
            }
        }
    }

    ~Udp_server()
    {}
private:
    string _ip;
    uint16_t _port;
    int _sockfd;
};